package com.ruoyi.central.utils;

import com.ruoyi.central.cmd.AbstractTaskCmd;
import com.ruoyi.central.domain.TopCentralTaskCmd;
import com.ruoyi.central.domain.TopCentralTaskCmdRun;
import com.ruoyi.central.enums.OperationTypeEnum;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.EnumUtils;
import com.ruoyi.common.utils.bean.InvokeUtils;
import com.ruoyi.common.utils.spring.SpringUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @Classname CmdInvokeUtil
 * @Author: sunluquan
 * @Date: 2022/6/13 15:06
 * @Description TODO
 * 指令执行工具
 */
public class CmdInvokeUtil {

    /**
     * 执行方法
     *
     * @param taskCmdRun 任务执行指令对象
     */
    public static void invokeMethod(TopCentralTaskCmdRun taskCmdRun) throws Exception{

        TopCentralTaskCmd taskCmd = taskCmdRun.getTaskCmd();

        String invokeTarget = taskCmd.getExecutable();
        String params = taskCmdRun.getArgs();
        List<Object[]> methodParams = null;
        Object target = null;
        String methodName = null;


        if(StringUtils.isNotEmpty(params)){
            methodParams = InvokeUtils.getMethodParams(params);
        }
        if(!InvokeUtils.isValidClassName(invokeTarget)){
            target = SpringUtils.getBean(invokeTarget);
        }else{
            target = Class.forName(InvokeUtils.getBeanName(invokeTarget)).newInstance();

        }
        methodName = InvokeUtils.getMethodName(invokeTarget);

        //如果当前对象 类型为 AbstractTaskCmd
        if(target instanceof AbstractTaskCmd){

            AbstractTaskCmd abstractTaskCmd = (AbstractTaskCmd)target;

            abstractTaskCmd.init(taskCmd,taskCmdRun,InvokeUtils.getMethodParams(methodParams));

            abstractTaskCmd.performBefore();

            abstractTaskCmd.perform();

            abstractTaskCmd.performAfter();

        }else{
            InvokeUtils.invokeMethod(target,methodName,methodParams);
        }
    }
}
